
let fs = require("fs");

let mysqlModule = require("mysql");

let connection = null;

let mysql = {


    init: function demo() {
        connection = mysqlModule.createConnection({ host: '127.0.0.1', user: 'root', password: 'root', database: 'yiqing' });

    },

    unuseQuery: function (sql, value, res) {


        mysql.init()
        connection.connect();

        /**
         * 推荐使用占位符方式查询，占位符可以防止 sql注入 占了 80%漏洞都是sql
         */
        connection.query(sql, value, function (err, result) {

            let html = '';


            for (let val in result) {
                html += '<tr>'
                html += '<td>' + result[val].city + "</td>"
                html += '<td>' + result[val].nums + "</td>"
                html += '</tr>'

            }

            fs.readFile("./home/html/index.html", function (err, data) {
                console.log(err);
                let datas = data.toString();
                let formatHtml = datas.replace("{{result}}", html);
                connection.end();
                res.write(formatHtml);
                res.end();

            })

        })

    },

    query: function name(sql, value) {

        let promise = new Promise(function (resolve, reject) {

            mysql.init();
            connection.connect();
            /**
             * 推荐使用占位符方式查询，占位符可以防止 sql注入 占了 80%漏洞都是sql
             */
            connection.query(sql, value, function (err, result) {

                if (err) {
                    console.log(err.message);
                    //reject(err.message)
                } else {

                    //setTimeout(function () {//模拟数据的慢查询
                        resolve(result);
                    //},5000)
                   
                }

                connection.end();
            })


        })
        return promise;

    }







}

module.exports = mysql;